#include "stdafx.h"
#include "CheckBoxItemdelegate.h"
#include <QApplication>
#include <QMouseEvent>

static QRect CheckBoxRect(const QStyleOptionViewItem &view_item_style_options)  
{  
	QStyleOptionButton check_box_style_option;  
	QRect check_box_rect = QApplication::style()->subElementRect(  
		QStyle::SE_CheckBoxIndicator,  
		&check_box_style_option);  

	QPoint check_box_point(view_item_style_options.rect.x() +  
		view_item_style_options.rect.width() / 2 -  
		check_box_rect.width() / 2,  
		view_item_style_options.rect.y() +  
		view_item_style_options.rect.height() / 2 -  
		check_box_rect.height() / 2);  
	return QRect(check_box_point, check_box_rect.size());  
}  

CheckBoxItemdelegate::CheckBoxItemdelegate(QObject *parent)
	: QStyledItemDelegate(parent)
{
	m_bEnable = true;
}

CheckBoxItemdelegate::~CheckBoxItemdelegate()
{

}

void CheckBoxItemdelegate::setEnable( bool bEnable )
{
	m_bEnable = bEnable;
}

void CheckBoxItemdelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
	if(index.column() == m_nColumnIndex)    
	{    
		bool checked = index.model()->data(index, Qt::CheckStateRole).toBool();  
		QStyleOptionButton check_box_style_option;    
		check_box_style_option.state |= QStyle::State_Enabled;    
		if(checked)    
		{    
			check_box_style_option.state |= QStyle::State_On;    
		}    
		else    
		{    
			check_box_style_option.state |= QStyle::State_Off;    
		}    
		check_box_style_option.rect = CheckBoxRect(option);    
		QApplication::style()->drawControl(QStyle::CE_CheckBox,&check_box_style_option,painter);    
	}  
}

bool CheckBoxItemdelegate::editorEvent( QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index )
{
	QRect decorationRect = option.rect;

	QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
	QRect chkRect = CheckBoxRect(option);

	if (event->type() == QEvent::MouseButtonPress && chkRect.contains(mouseEvent->pos()) && m_bEnable)
	{
		if (index.column() == m_nColumnIndex)
		{
			bool data = model->data(index, Qt::CheckStateRole).toBool();
			model->setData(index, !data, Qt::UserRole);
		}
	}

	return QStyledItemDelegate::editorEvent(event, model, option, index);
}

QSize CheckBoxItemdelegate::sizeHint( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
	if(index.column() == m_nColumnIndex)
	{
		//return QSize(50,option.rect.height()) ;
	}
	return QStyledItemDelegate::sizeHint(option,index);
}

void CheckBoxItemdelegate::setColumnIndex( int nIndex )
{
	m_nColumnIndex = nIndex;
}
